package com.aerors.DataProcess;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ProcessBuilderTest {

	public static void main(String[] args) {
		
		int minzoom = 5;
		int maxzoom = 10 ;
		String tileDir = "C:\\data\\dem\\CTBTiles";
		int threadNum = 5;
		String demPath = "C:\\data\\dem\\DEM4326.tif";
		
		List<String> command = new ArrayList<>();
//		command.add("ctb-tile");
//		command.add("-o");
//		command.add(tileDir);
//		command.add("-c");
//		command.add(String.valueOf(threadNum));
//		command.add("-s");
//		command.add(String.valueOf(maxzoom));
//		command.add("-e");
//		command.add(String.valueOf(minzoom));
//		command.add(demPath);
		command.add("tskill");
		command.add("chrome");
		
		ProcessBuilder pBuilder = new ProcessBuilder(command);

		try {
			Process p = pBuilder.start();
			if (p.isAlive()) {
				p.waitFor();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void killTask(String taskName) {
		String taskListCommand = "tasklist | findstr " + taskName;
		try {
			Process p = Runtime.getRuntime().exec(taskListCommand);
			
			InputStream error = p.getErrorStream();
			InputStream is = p.getInputStream();
			byte[] b = new byte[1024];
			int readbytes = -1;
			try {
				while ((readbytes = error.read(b)) != -1) {
					String rawStr = new String(b, 0, readbytes,"ISO-8859-1");
					System.out.println("标准错误输出信息：" + new String(rawStr.getBytes(),"GBK"));
				}
				while ((readbytes = is.read(b)) != -1) {
					String msg = new String(b, 0, readbytes);
					System.out.println("标准输出信息：" + msg);
				}
			} catch (IOException e) {
				System.out.println("等待进程结束出现错误！");
				e.printStackTrace();
			} finally {
				try {
					error.close();
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
			
			if (p.isAlive()) {
				p.waitFor();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public static int doWaitFor(Process process) {
		int exitValue = -1; // returned to caller when p is finished
		InputStream error = process.getErrorStream();
		InputStream is = process.getInputStream();
		byte[] b = new byte[1024];
		int readbytes = -1;
		try {
			while ((readbytes = error.read(b)) != -1) {
				System.out.println("标准错误输出信息：" + new String(b, 0, readbytes,"GBK"));
			}
			while ((readbytes = is.read(b)) != -1) {
				System.out.println("标准输出信息：" + new String(b, 0, readbytes));
			}
		} catch (IOException e) {
			System.out.println("等待进程结束出现错误！");
			e.printStackTrace();
		} finally {
			try {
				error.close();
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		return exitValue;
	}
}
